#!/usr/bin/python
from xml.etree.ElementTree import ElementTree, dump
import sys


class ConfigError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)
    

class CivPbemConfig:
    
    tree = None
    version = None
    user = None
    password = None
    url = None
    file_path = None
    game_name = None
    message_to_next_user = None
    log_level = None
    log_file = None

    #initializer accepts either a file name (str) or a file object
    def __init__(self, xml_file="config.xml"):
        self.parse_file (xml_file)
    #initializer is the same as above, but also accepts a file object to log info into.
    def __init__(self, xml_file="config.xml", log_file):
        self.add_log_file(log_file)
        self.parse_file (xml_file)
    #default print function
    def __str__(self):
        output= "user: " + self.user
        output = output + "\npassword: " + self.password
        output = output + "\nurl: " + self.url
        output = output + "\nfile path: " + self.file_path
        output = output + "\ngame name: " + self.game_name
        output = output + "\nmessage: " + self.message_to_next_user
        output = output + "\nlog_level: " + repr(self.log_level)
        return (output)
    #Function to add a log file that output is dumped into.
    def add_log_file(log_file):
        if (type(log_file).__name__ == 'file'):
            self.log_file = log_file
        else:
            raise ConfigError ("Expects a file object that is already opened for write")

    #Function to dump what the ElementTree contains.
    def dump_file_contents(self):
        dump (self.tree)

    #Function to load a new xml file for parsing
    def parse_file(self, xml_file="config.xml"):
        self.tree = ElementTree()
        if ( (type(xml_file).__name__ == 'file') or (type(xml_file).__name__ == 'str')):
            self.tree.parse(xml_file)
        else:
            print "xml_file was not a string or file object, using config.xml by default"
            self.tree.parse("config.xml")

        root_el = self.tree.getroot()
        if (root_el.tag != "civ_pbem_upload"):
            raise ConfigError ("This is not a civ_pbem_upload configuration file")

        self.__parse_version()
        self.__parse_user()
        self.__parse_password()
        self.__parse_url()
        self.__parse_path()
        self.__parse_game_name()
        self.__parse_message()
        self.__parse_log_level()




#All of these functions are private functions that actually parse the data from the xml tree
    def __parse_version(self):
        root_element = self.tree.getroot()
        if (root_element != None):
            self.version = int(root_element.get("version"))
        else:
            raise ConfigError("Config file is not properly formatted")

    def __parse_user(self):
        user_element = self.tree.find("user")
        if (user_element != None):
            self.user = user_element.text
            if (self.user != None):
                self.user = self.user.strip()
            else:
                raise ConfigError("User name not found")
        else:
            raise ConfigError("User name not found")
    
    def __parse_password(self):
        password_element = self.tree.find("password")
        if (password_element != None):
            self.password = password_element.text
            if (self.password != None):
                self.password = self.password.strip()
            else:
                raise ConfigError("Password not found")
        else:
            raise ConfigError("Password not found")

    def __parse_url(self):
        submit_url_element = self.tree.find("submit_url")
        if (submit_url_element != None):
            self.url = submit_url_element.text
            if (self.url != None):
                self.url = self.url.strip()
                if (self.url == ""):
                    #default to pbemtracker url
                    print "Submit Url not found, using default."
                    self.url = 'http://pbemtracker.com/submitturn.php?gameID=95'
            else:
                #default to pbemtracker url
                print "Submit Url not found, using default."
                self.url = 'http://pbemtracker.com/submitturn.php?gameID=95'
        else:
            #default to pbemtracker url
            print "Submit Url not found, using default."
            self.url = 'http://pbemtracker.com/submitturn.php?gameID=95'

    def __parse_path(self):
        file_path_element = self.tree.find("file_path")
        if (file_path_element != None):
            self.file_path = file_path_element.text
            if (self.file_path != None):
                self.file_path = self.file_path.strip()
            else:
                print ("File path not found, using current directory")
                self.file_path = ""
        else:
            print ("File path not found, using current directory")
            self.file_path = ""
    
    def __parse_game_name(self):
        game_name_element = self.tree.find("game_name")
        if (game_name_element != None):
            self.game_name = game_name_element.text
            if (self.game_name != None):
                self.game_name = self.game_name.strip()
            else:
                raise ConfigError("Game name not found")
        else:
            raise ConfigError("Game name not found")

    def __parse_message(self):
        message_element = self.tree.find("message_to_next_user")
        if (message_element != None):
            self.message_to_next_user = message_element.text
            if (self.message_to_next_user != None):
                self.message_to_next_user = self.message_to_next_user.strip()
                if (self.message_to_next_user == "") or (self.message_to_next_user == None):
                    self.message_to_next_user = self.user + " forgot to fill in a personalized message. For shame!"
            else:
                self.message_to_next_user = self.user + " forgot to fill in a personalized message. For shame!"
        else:
            self.message_to_next_user = self.user + " forgot to fill in a personalized message. For shame!"


    def __parse_log_level(self):
        log_level_element = self.tree.find("log_level")
        if (log_level_element != None):
            self.log_level = log_level_element.text
            if (self.log_level != None):
                self.log_level = self.log_level.strip()
            else:
                self.log_level = 0
        else:
            self.log_level = 0



